import logging
from flask import Blueprint, request, current_app
from app.service.alpha_service import calculate_factors,plot_factors,fetch_single_stock,calculate_growth_momentum_factor,calculate_inflation_spread_factor
import app.utils as utils
from flask_caching import Cache

# 创建蓝图对象
alpha_controller = Blueprint('alpha_controller', __name__)
cache = Cache(config={'CACHE_TYPE': 'SimpleCache'})

@alpha_controller.before_app_request
def init_cache():
    cache.init_app(current_app)

@alpha_controller.before_request #请求处理前记录请求信息
def log_request_info():
    current_app.logger.info(f"收到请求: {request.method} {request.url}")

@alpha_controller.after_request #响应返回后记录响应状态
def log_response_info(response):
    current_app.logger.info(f"响应状态码: {response.status_code}")
    return response

@alpha_controller.post('/cal_alpha')
def caculate_alpha():
    data = request.get_json()
    code = data.get("stock")
    print(code)
    try:
        current_app.logger.info("开始更新数据...")
        print('开始存入数据库')
        tickers = fetch_single_stock(code)
        print(tickers.head())
        print("----finifh ticker")
    except Exception as e:
        current_app.logger.exception("更新股票数据失败")
        return utils.error("股票数据更新失败", status=500,code=1)
    try:
        factor_list = calculate_factors(tickers)
    except Exception as e:
        current_app.logger.exception("更新股票数据失败")
        return utils.error("因子计算失败", status=500,code=1)
    try:
        growth_monument = calculate_growth_momentum_factor()
    except Exception as e:
        current_app.logger.exception("动量因子计算失败")
        return utils.error("动量因子计算失败", status=500,code=1)
    try:
        inflation_spread = calculate_inflation_spread_factor()
    except Exception as e:
        current_app.logger.exception("通货因子计算失败")
        return utils.error("通货因子计算失败", status=500,code=1)
    try:
        img = plot_factors(factor_list,code,growth_monument,inflation_spread)
        if img is None:
            return utils.error(f"未找到股票 {code} 的数据", status=404, code=1)
        return utils.success({
            "image": f"data:image/png;base64,{img}",
            "stock_code": code
        }, message="图表生成成功")
    except Exception as e:
        current_app.logger.exception("图表生成失败")
        return utils.error("图表生成失败", code=1, status=500)


















